package com.jdew.thkj.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.jdew.thkj.R;
import com.jdew.thkj.activity.AboutActivity;
import com.jdew.thkj.activity.BaoBiaoActivity;
import com.jdew.thkj.activity.BindShangJiActivity;
import com.jdew.thkj.activity.ChongZhiActivity;
import com.jdew.thkj.activity.CommonWebView;
import com.jdew.thkj.activity.CustomInvitationCodeActivity;
import com.jdew.thkj.activity.FanKuiActivity;
import com.jdew.thkj.activity.FansActivity;
import com.jdew.thkj.activity.FansTeamActivity;
import com.jdew.thkj.activity.ImproveActivity;
import com.jdew.thkj.activity.KeFuActivity;
import com.jdew.thkj.activity.LoginActivity;
import com.jdew.thkj.activity.MainActivity;
import com.jdew.thkj.activity.MessageCenterActivity;
import com.jdew.thkj.activity.MineErCodeActivity;
import com.jdew.thkj.activity.OnlineUpgradeActivity;
import com.jdew.thkj.activity.SetingTwoLevelActivity;
import com.jdew.thkj.activity.ShouCangActivity;
import com.jdew.thkj.base.BaseFragment;
import com.jdew.thkj.bean.NewCodeBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.CleanCacheUtil;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.view.CircleImageView;
import com.jdew.thkj.view.GlideCircleTransform;

import java.io.File;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

/**
 * Created by yangzai on 2018/1/23 0023.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.logo)
    CircleImageView logo;
    @Bind(R.id.shoucang)
    LinearLayout shoucang;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.clear)
    LinearLayout clearCacheView;
    @Bind(R.id.regist_ma)
    TextView registMa;
    @Bind(R.id.fuzhi)
    TextView fuzhi;
    @Bind(R.id.about)
    LinearLayout about;
    @Bind(R.id.baobiao)
    LinearLayout baobiao;
    @Bind(R.id.inviter_view)
    LinearLayout inviterView;
    @Bind(R.id.bind)
    LinearLayout bind;
    @Bind(R.id.message)
    ImageView message;
    @Bind(R.id.setting)
    ImageView setting;
    @Bind(R.id.gonglue)
    ImageView gonglue;
    @Bind(R.id.question)
    ImageView question;
    @Bind(R.id.kefu)
    ImageView kefu;
    @Bind(R.id.gonggao)
    LinearLayout gonggao;
    @Bind(R.id.fankui)
    LinearLayout fankui;
    @Bind(R.id.fans)
    LinearLayout fans;
    @Bind(R.id.yuer)
    TextView yuer;
    @Bind(R.id.chongzhi_view)
    LinearLayout chongzhi_view;
    @Bind(R.id.chongzhi)
    TextView chongzhi;
    @Bind(R.id.inviter)
    ImageView inviter;
    @Bind(R.id.level)
    ImageView level;
    @Bind(R.id.line)
    View line;
    @Bind(R.id.password)
    LinearLayout password;
    @Bind(R.id.up)
    LinearLayout up;
    @Bind(R.id.theme)
    RelativeLayout theme;
    @Bind(R.id.view)
    LinearLayout view;
    @Bind(R.id.minviter_view)
    LinearLayout minviterView;
    @Bind(R.id.findOrderNo)
    LinearLayout findOrderNo;
    //调用照相机返回图片临时文件
    private File tempFile;
    private MainActivity activity;
    private String photoPath;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void onCreateViewT() {
    }

    @Override
    public void initData() {
        clearCacheView.setOnClickListener(this);
        fuzhi.setOnClickListener(this);
        logo.setOnClickListener(this);
        about.setOnClickListener(this);
        shoucang.setOnClickListener(this);
        baobiao.setOnClickListener(this);
        bind.setOnClickListener(this);
        setting.setOnClickListener(this);
        message.setOnClickListener(this);
        gonglue.setOnClickListener(this);
        question.setOnClickListener(this);
        kefu.setOnClickListener(this);
        chongzhi.setOnClickListener(this);
        gonggao.setOnClickListener(this);
        fankui.setOnClickListener(this);
        fans.setOnClickListener(this);
        inviter.setOnClickListener(this);
        password.setOnClickListener(this);
        minviterView.setOnClickListener(this);
        up.setOnClickListener(this);
        findOrderNo.setOnClickListener(this);
        //创建拍照存储的临时文件
        createCameraTempFile(savedInstanceState);
    }

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.gonglue: {
                Intent in = new Intent(activity, CommonWebView.class);
                in.putExtra("url", "http://www.taohuikeji.com/Attachment/gonglue.jpg");
                in.putExtra("title", "新手攻略");
                startActivity(in);
            }
            break;
            case R.id.question: {
                Intent in = new Intent(activity, CommonWebView.class);
                in.putExtra("url", "http://www.taohuikeji.com/tlhweb/problem.html");
                in.putExtra("title", "常见问题");
                startActivity(in);
            }
            break;
            case R.id.kefu: {
                startActivity(new Intent(activity, KeFuActivity.class));
            }
            break;
            case R.id.gonggao: {
                Intent in = new Intent(activity, CommonWebView.class);
                in.putExtra("url", "http://www.taohuikeji.com/Attachment/gfgg.jpg");
                in.putExtra("title", "官方公告");
                startActivity(in);
            }
            break;
            case R.id.fankui: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                    return;
                }
                startActivity(new Intent(activity, FanKuiActivity.class));
            }
            break;
            case R.id.fuzhi: {
                RegexValidateUtils.copyText(activity, registMa.getText().toString());
                ToastUtils.getInstance(activity).showMessage("复制成功!");
            }
            break;
            case R.id.logo: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, ImproveActivity.class));
                }
            }
            break;
            case R.id.inviter: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                    return;
                }
                Intent in = new Intent(activity, MineErCodeActivity.class);
                in.putExtra("url", photoPath);
                in.putExtra("code", registMa.getText().toString());
                startActivity(in);
            }
            break;
            case R.id.fans: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                    return;
                } else if (sp.getString("SpareTwo", "").equals("1")) {
                    Intent in = new Intent(activity, FansActivity.class);
                    startActivity(in);
                } else {
                    Intent in = new Intent(activity, FansTeamActivity.class);
                    startActivity(in);
                }
            }
            break;
            case R.id.clear: {
                try {
                    ToastUtils.getInstance(activity).showMessage("清理了" + CleanCacheUtil.getTotalCacheSize(activity) + "缓存");
                    CleanCacheUtil.clearAllCache(activity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            break;
            case R.id.shoucang: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, ShouCangActivity.class));
                }
            }
            break;
            case R.id.about: {
                startActivity(new Intent(activity, AboutActivity.class));
            }
            break;
            case R.id.baobiao: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, BaoBiaoActivity.class));
                }

            }
            break;
            case R.id.up: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, OnlineUpgradeActivity.class));
                }

            }
            break;
            case R.id.chongzhi: {
                startActivity(new Intent(activity, ChongZhiActivity.class));
            }
            break;
            case R.id.bind: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, BindShangJiActivity.class));
                }
            }
            break;
            case R.id.minviter_view: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, CustomInvitationCodeActivity.class));
                }
            }
            break;
            case R.id.setting: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, ImproveActivity.class));
                }
            }
            break;
            case R.id.message: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, MessageCenterActivity.class));
                }
            }
            break;
            case R.id.password: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    startActivity(new Intent(activity, SetingTwoLevelActivity.class));
                }
            }
            break;
            case R.id.findOrderNo: {
                Intent in = new Intent(activity, CommonWebView.class);
                in.putExtra("url", "http://www.taohuikeji.com/h5Web/app_orderfind/Index.html");
                in.putExtra("title", "订单找回");
                startActivity(in);
            }
            break;
            default:
                break;
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("tempFile", tempFile);
    }


    /**
     * 创建调用系统照相机待存储的临时文件
     *
     * @param savedInstanceState
     */
    private void createCameraTempFile(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.containsKey("tempFile")) {
            tempFile = (File) savedInstanceState.getSerializable("tempFile");
        } else {
            tempFile = new File(checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"),
                    System.currentTimeMillis() + ".jpg");
        }
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AlibcTradeSDK.destory();
    }

    @Override
    public void onResume() {
        super.onResume();
        activity = (MainActivity) getActivity();
        sp = activity.getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        OutUserCode();
        photoPath = sp.getString("UserImgUrl", "");
        if (null == sp.getString("SpareTwo", "") || sp.getString("SpareTwo", "").equals("")) {
            view.setVisibility(View.GONE);
            chongzhi_view.setVisibility(View.GONE);
            bind.setVisibility(View.GONE);
            name.setText("未登录");
            line.setVisibility(View.GONE);
            level.setVisibility(View.GONE);
            inviterView.setVisibility(View.INVISIBLE);
            up.setVisibility(View.GONE);
        } else {
            view.setVisibility(View.VISIBLE);
            fans.setVisibility(View.VISIBLE);
            GetLevel();
            if (sp.getString("SpareTwo", "").equals("1")) {
                yuer.setVisibility(View.VISIBLE);
                bind.setVisibility(View.GONE);
                baobiao.setVisibility(View.GONE);
                up.setVisibility(View.GONE);
                password.setVisibility(View.GONE);
                chongzhi_view.setVisibility(View.VISIBLE);
                GetUserMoney();
            } else {
                if (sp.getString("SpareTwo", "").equals("4") || sp.getString("SpareTwo", "").equals("5")) {
                    up.setVisibility(View.VISIBLE);
                }
                chongzhi_view.setVisibility(View.GONE);
                yuer.setVisibility(View.GONE);
                password.setVisibility(View.VISIBLE);
                if ((null == sp.getString("UserSjPhone", "") || sp.getString("UserSjPhone", "").equals(""))) {
                    bind.setVisibility(View.VISIBLE);
                } else {
                    bind.setVisibility(View.GONE);
                }
            }
            inviterView.setVisibility(View.VISIBLE);
            name.setText("欢迎您:" + sp.getString("userPhone", ""));
        }
    }

    public void GetUserMoney() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetUserMoney(sp.getString("userPhone", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.e("sssssssss", e.toString());
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    yuer.setText("余额:" + obj.getString("data") + "元");
                }
            }
        });
    }

    public void GetLevel() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetLevel(sp.getString("userPhone", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.e("sssssssssssssss", e.toString());
            }

            @Override
            public void onNext(JSONObject json) {
                if (photoPath.equals("")) {
                    logo.setImageResource((R.mipmap.default_icon));
                } else {
                    RequestOptions options = new RequestOptions().priority(Priority.HIGH);
                    Glide.with(activity.getApplicationContext()).load(photoPath).apply(options).apply(bitmapTransform(new GlideCircleTransform(activity))).into(logo);
                }
                if (json.getString("message").equals("铜牌教练")) {
                    level.setImageResource(R.mipmap.lv4);
                } else if (json.getString("message").equals("银牌教练")) {
                    level.setImageResource(R.mipmap.lv5);
                } else if (json.getString("message").equals("分公司")) {
                    level.setImageResource(R.mipmap.lv6);
                } else if (json.getString("message").equals("股东")) {
                    level.setImageResource(R.mipmap.lv7);
                } else if (json.getString("message").equals("超级教练")) {
                    level.setImageResource(R.mipmap.lv3);
                } else if (json.getString("message").equals("普通惠员")) {
                    level.setImageResource(R.mipmap.lv1);
                } else if (json.getString("message").equals("高级惠员")) {
                    level.setImageResource(R.mipmap.lv2);
                } else if (json.getString("message").equals("预备子公司")) {
                    level.setImageResource(R.mipmap.lv8);
                }
            }
        });
    }

    public void OutUserCode() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("Id", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).OutUserCode(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Id" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<NewCodeBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(NewCodeBean bean) {
                if (bean.getCode().equals("0")) {
                    registMa.setText(bean.getData().getUserCode());
                    editor.putString("newUserCode", bean.getData().getUserCode());
                    editor.apply();
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
